// pages/home/home.js
const app = getApp()
const AV = require("../../utils/av-weapp-min.js");
var util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    feeds : [], //本地测试数据
    rooms : [], //网络数据
    searchText : '',
    geo : {},
    curGeo: {},
    timePrice: null,
    likeIcon : "../../images/dislike.png",
    collects : [],
    //Ivan.Wang
    isSearchVisible: false,
    currentTab: 0,
    slider_value: 0,
    now_price: "￥0-￥不限",
    objectArray: [
      { id: 0, "info": '房东直租', "ischoice": false },
      { id: 1, "info": '可做饭', "ischoice": false },
      { id: 2, "info": '可装修', "ischoice": false },
      { id: 3, "info": '设施齐全', "ischoice": false },
    ],
    objectArray2: [
      { id: 0, "info": '发布新→旧', "ischoice": true },
      { id: 1, "info": '价格低→高', "ischoice": false },
    ],
    isHidden: true,
    titleMsg: " ",
    inputHidden: false,
    cancleBtn: false,
    inputPlaceHolder: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.userInfo) {
      console.log(app.globalData.userInfo)
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var homeDatas = util.getHomeData();
    // console.log(homeDatas);
    
    this.setData({
      feeds : homeDatas.data,
    });
    var self = this;
    wx.showLoading({
      title: '拼命加载中...',
    });
    new AV.Query('RentRoom')
      // .descending('createdAt')
      .limit(10)
      .find()
      .then(function(rooms){
        wx.hideLoading();
        self.pushData(rooms);
        })
      .catch(console.error);
    this.loadCollect();
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  upper: function () {
    wx.showNavigationBarLoading()
    this.refresh();
    console.log("upper");
    setTimeout(function () { wx.hideNavigationBarLoading(); wx.stopPullDownRefresh(); }, 2000);
  },
  lower: function (e) {
    wx.showNavigationBarLoading();
    var that = this;
    setTimeout(function () { wx.hideNavigationBarLoading(); that.nextLoad(); }, 1000);
    console.log("lower")
  },
  //网络请求数据, 实现首页刷新
  refresh0: function () {
    // var index_api = '';
    // util.getData(index_api)
    //   .then(function (data) {
    //     //this.setData({
    //     //
    //     //});
    //     console.log(data);
    //   });
  },//使用本地 fake 数据实现刷新效果
  refresh: function () {
    // var feed = util.getData2();
    console.log("loaddata");
    // var feed_data = feed.data;
    // this.setData({
    //   feed: feed_data,
    //   feed_length: feed_data.length
    // });
  },
  searchInput: function(e){
    this.setData({
      searchText : e.detail.value,
    });
    console.log(e.detail.value);
  },
  onSearch : function() { //search info from server
    var searchText = this.data.searchText;
    console.log(searchText);
    
    wx.showNavigationBarLoading();
    var query = new AV.Query('RentRoom');
    if (!util.isEmpty(searchText)) {
      query.contains('title', searchText);
    }
    query.find()
    .then(rooms => {
      this.pushData(rooms);
      this.loadCollect();
      })//this.updateData(rooms))
    .catch(function(){
      wx.hideNavigationBarLoading();
      console.error
      });
    
  },
  updateData : function(results){
    wx.hideNavigationBarLoading();
    if (undefined != results) {
      this.setData({
        rooms : results,
      });
    }
  },
  loadByLocation : function() {
    var curGeo = app.globalData.geo;
    var latitude = curGeo.latitude;
    var longitude = curGeo.longitude;
    console.log('latitude : ' +latitude+ " longitude: "+longitude);
    var self = this;
    var query = new AV.Query('RentRoom');
    var point = new AV.GeoPoint(latitude, longitude);
    query.withinKilometers('location', point, 2.0);
    query.find().then(function (results) {
      console.log("home kilometer->", results);
      for (var i = 0; i < results.length; i++) {
        var item = results[i];
        var qLatitude = item.attributes.location.latitude;
        var qLongitude = item.attributes.location.longitude;
        // console.log(qLatitude + " " + qLongitude);
        // console.log("current: " + curGeo.latitude + " " + curGeo.longitude);
        var distance = util.getGreatCircleDistance(qLatitude, qLongitude, curGeo.latitude, curGeo.longitude);
        // console.log("distance : " + parseInt(distance));
        item.set('distance', parseInt(distance));
      }
      console.log(results);
      self.setData({
        rooms: results,
      });
    }, function (error) {
      console.log(error);
    });
  },
  pushData : function(dataJson) {
    wx.hideNavigationBarLoading();
    var curGeo = app.globalData.geo;
    for (var i = 0; i < dataJson.length; i++) {
      var item = dataJson[i];
      var qLatitude = item.attributes.location.latitude;
      var qLongitude = item.attributes.location.longitude;
      // console.log(qLatitude + " " + qLongitude);
      // console.log("current: " + curGeo.latitude + " " + curGeo.longitude);
      var distance = util.getGreatCircleDistance(qLatitude, qLongitude, curGeo.latitude, curGeo.longitude);
      // console.log("distance : " + parseInt(distance));
      item.set('distance', parseInt(distance));
      var tp = util.decodeTimePrice(item.attributes.timePrice);
      // console.log("decode tp => ", tp);
      item.set("tp", tp);
    }
    // console.log(dataJson);
    app.globalData.rooms = dataJson;
    this.setData({
      rooms : dataJson,
    });
  },
  doJump : function(e) { //跳转到详细页面
    console.log("dojump", e);
    let index = e.currentTarget.dataset.index;
    let id = e.target.id;
    let target = this.data.rooms[index];
    let lcUser = AV.User.current();
    let self = this;
    if ("2" === id) {
      console.log("------> onlike icon'd been clicked");
      if (!lcUser) return;
      let clts = this.data.collects;
      for (var i = 0; i < clts.length; i++) {
        if (clts[i].attributes.rentId == target.id) {
          // console.log("=======>", clts[i].id);
          this.cancelLike(clts[i].id);
          return;
        }
      }
      wx.showLoading();
      var Collect = AV.Object.extend('collect');
      var collect = new Collect();
      collect.set('rentId', target.id);
      collect.set("userId", lcUser.id);
      collect.save().then(function (clt) {
        wx.hideLoading();
        self.loadCollect();
         wx.showToast({
          title: '收藏成功!',
        });
      }, function (error) {
        wx.hideLoading();
        self.loadCollect();
        console.error(error);
      });
    }else {
      app.globalData.homeDetail = target;
      // console.log(target);
      wx.navigateTo({
        url: '../home_details/home_details?src=home',
      })
    }
    
  },
  netSaveCollect : function(userId, rentId) {

  },
  loadCollect : function() {
    let lcUser = AV.User.current();
    if (!lcUser) return;
    wx.showLoading();
    new AV.Query('collect')
      .equalTo("userId", lcUser.id)
      .limit(10)
      .find()
      .then(clts => {
        wx.hideLoading();
        // console.log("query user id: ", clts);
        if (clts && clts.length > 0) {
          app.globalData.collections = clts;
          let tRooms = this.data.rooms;
          if (tRooms && tRooms.length > 0) {
            for (var i = 0; i < this.data.rooms.length; i++) {
              let room = tRooms[i];
              let has = false;
              for (var j = 0; j < clts.length; j++) {
                // console.log("sub, ", room.id, clts[j].attributes.rentId);
                if (clts[j].attributes.rentId == room.id) {
                  has = true;
                }
              }
              if (has) {
                room.set("likeIcon", "../../images/like.png");
              } else {
                room.set("likeIcon", "../../images/dislike.png");
              }
            }
          }
          // console.log("trooms", tRooms);
          this.setData({
            rooms: tRooms,
            collects: clts,
          });
        }

      })
      .catch(error => {
        wx.hideLoading();
        });
  },

  //Ivan.Wang
  bindShowCover: function (e) {
    if (this.data.isSearchVisible) {
      return false;
    } else {
      this.setData({
        isSearchVisible: true
      })
    }
  },

  bindResetTap: function (e) {
    this.setData({
      isSearchVisible: true,
      currentTab: 0,
      slider_value: 0,
      now_price: "￥0-￥不限",
      objectArray: [
        { id: 0, "info": '房东直租', "ischoice": false },
        { id: 1, "info": '可做饭', "ischoice": false },
        { id: 2, "info": '可装修', "ischoice": false },
        { id: 3, "info": '设施齐全', "ischoice": false },
      ],
      objectArray2: [
        { id: 0, "info": '发布新→旧', "ischoice": true },
        { id: 1, "info": '价格低→高', "ischoice": false },
      ]

    });
  },

  /**
     * 点击遮罩层使搜索条件消失
     * @param  {[type]} e [description]
     * @return {[type]}   [description]
     */
  bindCoverTap: function (e) {
    // var anim = wx.createAnimation({
    //     duration: 300,
    //     timingFunction: "ease-in",
    // });
    // anim.opacity(0).step();
    this.setData({
      isSearchVisible: false,
      // coverAlphaAnim: anim.export()
    });

    this.doFilter();
  },

  swichNav: function (e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  sliderchange: function (e) {
    var current = e.detail.value;
    if (current <= 0 || current > 10000) {
      this.setData({
        now_price: "￥0-￥不限"
      });
    } else {
      this.setData({
        now_price: "￥0-￥" + current
      });
    }
  },

  bindChange: function (e) {
    this.setData({ currentTab: e.detail.current });
  },

  choiceNav: function (e) {
    var oIndex = parseInt(e.currentTarget.dataset.index);
    var array = this.data.objectArray;
    // console.log("index:" + oIndex);
    // console.log("oSelected:" + array[oIndex].ischoice);
    var oSelected = array[oIndex].ischoice
    // var oSelected = [`array[${oIndex}].ischoice`]
    //[`array[${oIndex}].ischoice`]
    if (oSelected) {
      console.log("ture");
      this.setData({
        ["objectArray[" + oIndex + "].ischoice"]: false
      })
    } else {
      console.log("false");
      this.setData({
        ["objectArray[" + oIndex + "].ischoice"]: true
      })
    }
  },

  choiceNav2: function (e) {
    var oIndex = parseInt(e.currentTarget.dataset.index);
    var array = this.data.objectArray2;
    // console.log("index:" + oIndex);
    // console.log("oSelected:" + array[oIndex].ischoice);
    var oSelected = array[oIndex].ischoice
    // var oSelected = [`array[${oIndex}].ischoice`]
    //[`array[${oIndex}].ischoice`]
    if (oSelected) {
      console.log("ture");
      this.setData({
        ["objectArray2[" + oIndex + "].ischoice"]: false
      })
    } else {
      console.log("false");
      this.setData({
        ["objectArray2[" + oIndex + "].ischoice"]: true
      })
    }
  },

  doJumpFillIn: function(e) {
    wx.navigateTo({
      url: '../fillin/fillin?src=home',
    })
  },
  callCloudFun : function() {
    AV.Cloud.run().then().catch();
  },

  /**
   * 
   */
  doFilter : function() {
    let endPrice = 5000;
    let condition = '';
    let priceDescending = false; //价格升序
    let timeDescending = true;//默认降序

    // let startDateQuery = new AV.Query('RentRoom');
    // startDateQuery.greaterThanOrEqualTo('price', startPrice);

    let priceQuery = new AV.Query('RentRoom');
    priceQuery.lessThan('price', endPrice);

    // var conditionQuery = new AV.Query('RentRoom');
    // conditionQuery.equalTo('condition', condition);

    let query = AV.Query.and(priceQuery);
    if (priceDescending) {
      query.addAscending('price');
    }else {
      query.addDescending('price');
    }
    if (timeDescending) {
      query.addDescending('createdAt');
    }else {
      query.addAscending('createdAt');
    }


    wx.showLoading({
      title: '查询中...',
    })
    query.find().then((res)=>{
      wx.hideLoading();
        if (res) {
          this.pushData(res);
          this.loadCollect();
        }
    }, (error)=>{
      wx.hideLoading()
    });
  }
  ,
  //测试dialog
  showCompomentDialog: function () {
    console.log('自定义input-dialog测试');
    var that = this;
    that.setData({
      isHidden: false,
      // titleMsg: "需要验证您的手机号",
      inputPlaceHolder: "请输入您的手机号",
      inputHidden: false,
      // cancleBtn: true,
    })
  },

  onMyEvent: function (e) {
    var that = this;
    console.log("e.detail :", e.detail)

    that.setData({
      isHidden: true,
      // inputHidden: false
    })
  },
  /** 取消收藏 */
  cancelLike : function(objId) {
    var collect = AV.Object.createWithoutData('collect', objId);
    collect.destroy().then((success)=> {
      // 删除成功
      this.loadCollect();
    }, function (error) {
      // 删除失败
    });
  }

})